import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
} from 'react-native';

import styles from './editOrderStyle';
import CustomListView from '../global/CustomListView';
import api from '../../services/api';
import _ from 'lodash';
import ToastTip from '../global/ToastTip';
// const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class HistoryAddrList extends Component {
    constructor(props) {
		super(props);

		this.state = {
			currentPage: 1,
            noData: false
		};

        // this._page = 0;
        this.totalpage = 0;
        this.pagesize = 10;
        this.list = [];

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentDidMount() {
        this.onLoad();
    }

    onLoad(){
        if(this.state.noData){
            this.setState({ noData: false});
        }

        this._historyAddrByList._pullToRefreshListView.beginRefresh(true);
    }

    componentWillUnmount () {

    }

    _onSearchResultListItemPress(rowData){
        let address_left = rowData.first_address.split('\n');
        let addressSecond = "";
        let addressFirst = address_left[0];
        if(address_left.length>1){
            addressSecond = address_left[1];
        }

        this.props.parent.setState({addressFirst,addressSecond, location: `${rowData.location_address}`});

        let start_latitude = parseFloat(rowData.location_address.split(',')[0]),
            start_longitude = parseFloat(rowData.location_address.split(',')[1]);
        if(start_latitude && start_longitude){
            this.props.parent._amap.setCenterCoordinate({
                latitude: start_latitude,
                longitude: start_longitude,
            });
        }
    }

    async _addAddrStore(rowData, sectionID, rowID){
        let status = this.list[rowID].status==1?0:1;
        let res = await api.post('/address/storeornot', {
                       status,
                       id: this.list[rowID].id
                    });

        if(res.data){
            let {actions, dispatch} = this.props;

            if(this.props.status == 1){//收藏地址
                _.pullAt(this.list, [rowID]);
                this.props.parent._historyListView && this.props.parent._historyListView.wrappedInstance.onLoad();
            }else{
                this.list[rowID].status = status;
                this.props.parent._storeListView && this.props.parent._storeListView.wrappedInstance.onLoad();
            }

            if(this.list.length == 0){//无数据后
                this.setState({noData: true});
                return;
            }

            this._historyAddrByList.setState({
                dataList: this.list,
                dataSource: this._historyAddrByList._dataSource.cloneWithRows(this.list),
            });
        }

    }

    async _getHistoryList(){
        let list;
        if(this.props.status == 1){//收藏地址
            list = await api.post('/address/storelist', {
                           page:1,
                           pagesize: this.pagesize
                        });
        }else{
            list = await api.post('/address/historylist', {
                           page:1,
                           pagesize: this.pagesize
                        });
        }

        if(list.cd == 1){
            this.refs.toast.show(list.msg);
            this._historyAddrByList._pullToRefreshListView.endRefresh(false);
            return;
        }

       if(Platform.OS == 'ios') {
           this._endHistoryList(list.data);
       } else {
           setTimeout(() => {
               this._endHistoryList(list.data);
           }, 300);
       }
    }

    // _updateListView(){
    //     let {actions, dispatch} = this.props;
    //     let action;
    //     if(this.props.status == 1){//收藏地址
    //         action = actions.address.store_change(this.list);
    //     }else {
    //         action = actions.address.history_change(this.list);
    //     }
    //
    //     dispatch(action);
    // }

    _endHistoryList(list){

        this.totalpage = list.total_page;
        this.list = list.res;

        if(this.list.length==0){
            this.setState({noData: true});
            return;
        }

        // this._updateListView();

        this._historyAddrByList.setState({
            dataList: list.res,
            dataSource: this._historyAddrByList._dataSource.cloneWithRows(list.res)
        });

        this.props.parent._activityIndicator.setState({ visible: false,});
        this._historyAddrByList._pullToRefreshListView.endRefresh(false);
    }

    async _retrieveNextPage() {
		if (this.state.currentPage !== this.totalpage) {
			// this.setState({
			// 	currentPage: this.state.currentPage + 1
			// });

			let page;
            page = this.state.currentPage + 1;
            this.setState({ currentPage: page });

            let list;
            if(this.props.status == 1){//收藏地址
                list = await api.post('/address/storelist', {
                               page:page,
                               pagesize: this.pagesize
                            });
            }else{
                list = await api.post('/address/historylist', {
                               page:page,
                               pagesize: this.pagesize
                            });
            }

            if(list.cd == 1){
                this.refs.toast.show(list.msg);
                this._historyAddrByList._pullToRefreshListView.endRefresh(false);
                return;
            }

        //    const data = this.list;
           const newData = list.data.res;
           newData.map((item, index) => this.list.push(item));

           this._historyAddrByList.setState({
               dataList: this.list,
               dataSource: this._historyAddrByList._dataSource.cloneWithRows(this.list),
           });
           this._historyAddrByList._pullToRefreshListView.endLoadMore(false);

        }else{
            this._historyAddrByList._pullToRefreshListView.endLoadMore(true);
        }
	}

    _onHistoryRefresh(){
        this._getHistoryList();
    }

    _onHistoryLoadMore(){
        this._retrieveNextPage();
    }

    _renderHistoryRow(rowData, sectionID, rowID){
        return (
            <TouchableOpacity
                style={styles.searchItem}
                activeOpacity={0.7}
                onPress={this._onSearchResultListItemPress.bind(this, rowData)}>
                <View style={{flexDirection: 'row',alignItems:'center', justifyContent:'space-between'}}>
                    <View style={{flexDirection: 'row',alignItems:'center',}}>
                        <Image source={require('../../../img/hk_map_poi_icon.png')} style={styles.leftImage}/>
                        <View style={{marginLeft: 10,}}>
                            <Text style={{fontSize: 13, color: '#555555',}}>{rowData.rowID}{rowData.first_address.length>20?rowData.first_address.substring(0,20)+"...":rowData.first_address}</Text>
                        </View>
                    </View>
                    <TouchableOpacity
                        style={{marginRight:20, width: 15, alignItems: 'flex-end', justifyContent: 'flex-end'}}
                        activeOpacity={0.7}
                        onPress={this._addAddrStore.bind(this, rowData, sectionID, rowID)}>
                        <View>
                            <Image source={rowData.status == 1? require('../../../img/hk_storeaddr_select_icon.png'):require('../../../img/hk_storeaddr_icon.png')} style={{width: 15, height: 15}}/>
                        </View>
                    </TouchableOpacity>
                </View>
            </TouchableOpacity>
        );
    }

    _renderNodata(){
        return (
            this.props.status==1?<View style={{alignItems:'center',justifyContent:'center',flex:1,backgroundColor:'#fff'}}>
                <Text style={{fontSize: 13, color: '#B5B5B5',}}>没有收藏的地址</Text>
                <View style={{flexDirection: 'row',alignItems:'center',justifyContent:'flex-end',}}>
                    <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10,}}>在历史地址中点击 </Text>
                    <Image source={require('../../../img/hk_storeaddr_icon.png')} style={{width:10,height:10,marginTop:10}}/>
                    <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10,}}> 可收藏地址</Text>
                </View>
            </View>:
            <View style={{alignItems:'center',justifyContent:'center',flex:1,backgroundColor:'#fff'}}>
                <Image source={require('../../../img/hk_nodata_icon.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>暂无历史记录哦~</Text>
            </View>
        );
    }

    render() {
        return (
            this.state.noData?this._renderNodata():
            <View style={{flex:1}}>
                <CustomListView
                    ref={ (component) => this._historyAddrByList = component }
                    onRefresh={this._onHistoryRefresh.bind(this)}
                    onLoadMore={this._onHistoryLoadMore.bind(this)}
                    renderRow ={this._renderHistoryRow.bind(this)}
                />
                <ToastTip ref="toast" offsetY={200}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
HistoryAddrList = connectHelper(state => state)(HistoryAddrList);

module.exports = HistoryAddrList;
